const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const noticeModel = require('../models/notice');

const router = express.Router();

//新增公告
router.post('/',(req,res,next)=>{
  const {title,content,author}=req.body;
  const id=uuid.v1();
  const pushTime=new Date();
  const notice=new noticeModel({id,title,content,author,pushTime});
  if(title&&content&&author){
    notice.save().then(data=>{
      if(data){
        res.json(Message(200,'发布成功！'));
      }
    })
  }else{
    res.json(Message(400,'发布失败！'));
  }
});

//删除公告
router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    noticeModel.deleteOne({ id }).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'));
      }else{
        res.json(Message(400,'删除失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
});

//修改公告
router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {content}=req.body;
  if(id){
    noticeModel.updateOne({id},{content}).then(data=>{
      if(data.acknowledged&&data.modifiedCount !== 0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
});

//查询公告
router.get('/',(req,res,next)=>{
  const {id,title}=req.query;
  if(id){//查询单个数据
    noticeModel.findOne({id}).then(data=>{
      if(data){
        res.json(Message(200,'',data._doc));
      }else{
        res.json(Message(400,'未查找到相关输！'));
      }
    })
  }else{//查询列表
    let {page,pageSize}=req.query;
    let regexp=new RegExp(title,'i');
    if(title&&page&&pageSize){//模糊查询列表
      noticeModel.find({$or: [{title:{$regex:regexp}}]}).count((err,count)=>{
        noticeModel.find({$or: [{title:{$regex:regexp}}]})
          .limit(pageSize)
          .skip((page-1)*pageSize)
          .then(data=>{
            res.json(MessageList(200,'',data,page,pageSize,count));
        })
      })
    }else if(!title&&page&&pageSize){//查询全部列表
      noticeModel.countDocuments((err,count)=>{
        noticeModel.find()
          .limit(pageSize)
          .skip((page-1)*pageSize)
          .then(data=>{
            res.json(MessageList(200,'',data,page,pageSize,count));
          })
      })
    }else if(!title&&!page&&!pageSize){
      noticeModel.find().then(data=>{
        res.json(MessageList(200,'',data,0,0,data.length))
      })
    }
  }
})

module.exports = router